package com.example.shiro_springboot.realm;

import com.example.shiro_springboot.entity.User;
import com.example.shiro_springboot.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    // 自定义授权方法：获取当前登录用户的角色、权限信息，返回给shiro用来进行授权认证
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("自定义授权方法");
        //1.获取当前用户的身份信息
        String principal = principalCollection.getPrimaryPrincipal().toString();

        //2.调用业务层获取用户的角色信息
        List<String> roleList = userService.getUserRoleInfo(principal);
        System.out.println("current user roleList = " + roleList);
        //2.5调用业务层获取用户的权限信息
        List<String> permissionList = userService.getPermissionsInfo(roleList);
        System.out.println("current user permissionList = " + permissionList);
        //3.创建对象，封装当前登录用户的角色、权限信息
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        // 4.存储角色
        info.addRoles(roleList);
        // 4.5 存储权限
        info.addStringPermissions(permissionList);
        // 5.返回信息
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 1.获取身份信息
        String principal = authenticationToken.getPrincipal().toString();
        // 2.调用业务层获取用户信息
        User user = userService.getUserInfoByName(principal);
        // 3.非空判断，将数据封装返回
        if (user != null) {
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                    authenticationToken.getPrincipal(),
                    user.getPwd(),
                    ByteSource.Util.bytes("salt"),
                    authenticationToken.getPrincipal().toString());
            return info;

        }
        return null;
    }
}
